﻿using System;
using System.Data;

namespace Cineplex.Contacts.Models
{
    public class ContactModelContextBase : IDisposable
    {
        private CineplexEntities _dataModel;        
        private IDbTransaction _transaction;
        public ContactModelContextBase()
        {
            if (_dataModel == null)
            {
                _dataModel = new CineplexEntities();

            }
        }

        public CineplexEntities DataModel
        {
            get { return _dataModel ?? (_dataModel = new CineplexEntities()); }
        }

        public void BeginTransaction()
        {
            // Start _trans
            _dataModel.Connection.Open();
            _transaction = _dataModel.Connection.BeginTransaction();
        }

        public void CommitTransaction()
        {
            // Start _trans                        
            if (_transaction != null && _dataModel.Connection.State != ConnectionState.Closed)
            {
                _transaction.Commit();
                _transaction.Dispose();
                _dataModel.Connection.Close();
            }
        }

        public void RollbackTransaction()
        {
            // Start _trans
            if (_transaction != null && _dataModel.Connection.State != ConnectionState.Closed)
            {
                _transaction.Rollback();
                _transaction.Dispose();                
            }
        }

        protected virtual void Dispose(bool isDispose)
        {
            if (isDispose)
            {
                _dataModel.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }
}

